from bs4 import BeautifulSoup

is_write_translate = False
source_path = "strings.xml"
source_string_path = "资源文件.txt"
translate_path = "xxxx.txt"
source_translate_path = "new_string.xml"


def write_to_file(path, text):
    with open(path, 'a', encoding='utf-8') as f:
        f.writelines(text + '\n')


def get_xml_string_to_file():
    file = open(source_path, 'r', encoding='utf-8')
    soup = BeautifulSoup(file, "html.parser")
    soup.contains_replacement_characters = False
    string_tag = soup.find_all('string')
    for content in string_tag:
        write_to_file(source_string_path, content.string)


def write_translate_to_file():
    file = open(source_path, 'r', encoding='utf-8')
    soup = BeautifulSoup(file, "html.parser")
    soup.contains_replacement_characters = False
    string_tag = soup.find_all('string')
    write_to_file(source_translate_path, "<resources>")
    with open(translate_path, 'r', encoding='utf-8') as file_object:
        lines = file_object.readlines()
    i = 0
    line_len = len(lines)
    while i < line_len:
        s = lines[i]
    if i < line_len - 1:
        s = s[:-1]
    content = string_tag[i]
    content.string = s
    write_to_file(source_translate_path, str(content))
    i += 1
    write_to_file(source_translate_path, "</resources>")


if __name__ == '__main__':
    temp_source_path = input("程序未做判空处理，确保输入有效，请输入原始文件路径:\n")
    if temp_source_path:
        source_path = temp_source_path
    flag = input("提取资源字符串请输入1， 整合翻译字符串请输入2: \n")
    if flag == '1':
        is_write_translate = False
    elif flag == '2':
        is_write_translate = True
    else:
        is_write_translate = False

    if is_write_translate:
        temp_translate_path = input("请输入翻译文件路径(txt 格式，不能有空行):\n")
        if temp_translate_path:
            translate_path = temp_translate_path
        temp_source_translate_path = input("请输入输出路径(xml):\n")
        if temp_source_translate_path:
            source_translate_path = temp_source_translate_path
            write_translate_to_file()
    else:
        temp_source_string_path = input("请输入输出路径(txt):\n")
        if temp_source_string_path:
            source_string_path = temp_source_string_path
        get_xml_string_to_file()

